package com.tedu.mall.controller;

import com.tedu.mall.mapper.ItemMapper;
import com.tedu.mall.pojo.Item;
import com.tedu.mall.pojo.ItemExample;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

//商品操作
@RestController
@CrossOrigin
public class ItemController {
    @Autowired
    ItemMapper itemMapper;
    //更新商品
    @RequestMapping("/item/update")
    //:1314/item/update?itemId=4
    //&categoryId=2&itemName=新名字
    //&itemPrice=99999&itemDesc=新的描述
    //&itemImage=9.jpg
    public String update(Item item){
        //update item set item_name=新名字,
        //where item_id=4
        int count=itemMapper
                .updateByPrimaryKey(item);
        if (count>=1){
            return "更新成功";
        }else {
            return "更新失败";
        }
    }
    //查询所有商品
    @RequestMapping("/item/selectAll")
    public List<Item> selectAll(){
        return itemMapper.selectByExample(null);
    }
    //删除
    @RequestMapping("/item/delete")
    //:1314/item/delete?itemId=5
    public String delete(Integer itemId){
        //delete from item where item_id=5
        int count=itemMapper
                .deleteByPrimaryKey(itemId);
        if (count>=1){
            return "删除成功";
        }else {
            return "删除失败";
        }

    }
    //添加商品
    @RequestMapping("/item/insert")
    /**
     * :1314/item/insert?categoryId=1&itemName=n1
     * &itemImage=1.jpg&itemPrice=90
     * &itemDesc=desc
     * */
    public String insert(Item item)
    {
        int count=itemMapper.insertSelective(item);
        if (count>=1){
            return "添加成功";
        }else{
            return "添加失败";
        }
    }
    //首页显示商品，用户单击一个商品，显示商品详情
    //根据商品编号查询商品
    @RequestMapping("/item/findByItemId")
    // :1314/item/findByItemId?id=2
    public Item findByItemId(Integer id){
        Item item=itemMapper.selectByPrimaryKey
                (id);
        return item;
    }
    //查询分类下的所有商品
    @RequestMapping("/item/findByCategoryId")
    // :1314/item/findByCategoryId?id=1
    public List<Item> findByCategoryId
    (Integer id){
        ItemExample itemExample=new ItemExample();
        ItemExample.Criteria criteria=
                itemExample.or();
        criteria.andCategoryIdEqualTo(id);
        List<Item> list=itemMapper
                .selectByExample(itemExample);
        return  list;

    }

}
